<template>
  <div></div>
</template>

<script>
export default {
  data() {
    return {
      code: this.$route.query.code,
      state: this.$route.query.state,
    };
  },
  methods: {
    bindWechat() {
      const { code, state } = this.$data;
      this.getUnionId(code).then((unionid) => {
        const type = decodeURIComponent(state).split(",")[0];
        if (type == "add_wechat") {
          let userid = decodeURIComponent(state).split(",")[1];
          let admin_name = decodeURIComponent(state).split(",")[2];
          let main_unionid=decodeURIComponent(state).split(",")[3];
          this.$axios({
            method: "post",
            url: "/api/adminapi/dispatcher",
            data: {
              action: "add",
              unionid: unionid,
              userid: userid,
              name: admin_name,
              openid:main_unionid
            },
          }).then((res) => {
            if (res.data.ret == 0) {
              this.$router.push("/mgr/communitymanagement");
              this.$message.success("绑定微信成功");
            } else {
              this.$router.push("/mgr/communitymanagement");
              this.$message.error(res.data.msg);
            }
          });
        } else if (type == "bind_wechat") {
          let username = decodeURIComponent(state).split(",")[1];
          this.$axios({
            method: "post",
            url: "/api/adminapi/addopenid",
            data: {
              username: username, //用户名
              openid: unionid,
            },
          }).then((res) => {
            if (res.data.ret == 0) {
              this.$router.push("/mgr/communitymanagement");
              this.$store.dispatch("resetUnionid", unionid);
              this.$message.success("绑定微信成功");
            } else {
              this.$router.push("/mgr/communitymanagement");
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    async getUnionId(code) {
      return new Promise((resolve) => {
        this.$axios({
          method: "get",
          url: "/wechat_api/sns/oauth2/access_token",
          params: {
            appid: "wx7870d5e16708e05e",
            secret: "5b3febb92f2ea96bb8348c45bb0e5b83",
            code: code,
            grant_type: "authorization_code",
          },
        }).then((res) => {
          resolve(res.data.unionid);
        });
      });
    },
  },
  mounted() {
    this.bindWechat();
  },
};
</script>

<style scoped>
</style>